<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderSn">
        <el-input
          v-model="queryParams.orderSn"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
    
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderSn" />
      <el-table-column label="批次" align="center" prop="pmsBatch.name" />
      <el-table-column label="用户帐号" align="center" prop="memberUsername" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <!-- <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="批次" prop="batchId" >
          <el-select style="width: 100%;" v-model="form.batchId" value-key="" placeholder="选择批次" clearable filterable @change="batchChange(form.batchId)">
            <el-option v-for="item in batchList"
              :key="item.batchId"
              :label="item.name"
              :value="item.batchId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-card shadow="always" :body-style="{ padding: '20px' }">
          <div slot="header">
            <span>商品</span>
            <el-button style="float: right;margin-right: 10px; padding: 3px 0" type="text" @click="addBatchProduct(form.batchId,form.orderId)">添加</el-button>
          </div>
           <div>
              <el-row :gutter="20" v-for="(itemF,index) in orderProductList" :key="index">
                <el-col :span="12" :offset="0">
                  <div>名称</div>
                  <div>
                    <el-select v-model="itemF.productId" value-key="" placeholder="选择商品" clearable filterable>
                      <el-option v-for="item in productList"
                        :key="item.productId"
                        :label="item.productName"
                        :value="item.productId">
                      </el-option>
                    </el-select>
                    
                  </div>
                </el-col>
                <el-col :span="12" :offset="0">
                  <div>数量</div>
              <div style="display: inline-flex">
                <el-input-number v-model="itemF.productNumber" size="normal" :min="0" :step="1" :controls="true" controls-position="right" style="width: 100%;">
                </el-input-number>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteProduct(index)">删除</el-button>
              </div>
                </el-col>
              </el-row>
              
           </div>
        </el-card>
        
        <!-- <el-form-item label="用户帐号" prop="memberUsername">
          <el-input v-model="form.memberUsername" placeholder="请输入用户帐号" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入订单总金额" />
        </el-form-item>
        <el-form-item label="采购价" prop="purchasePrice">
          <el-input v-model="form.purchasePrice" placeholder="请输入采购价" />
        </el-form-item>
        <el-form-item label="自动确认时间" prop="autoConfirmDay">
          <el-input v-model="form.autoConfirmDay" placeholder="请输入自动确认时间" />
        </el-form-item>
        <el-form-item label="确认收货时间" prop="receiveTime">
          <el-date-picker clearable
            v-model="form.receiveTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择确认收货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder ,getOrderProductList,addOrderProducts,updateOrderProducts} from "@/api/system/order";
import {getBatchListAll,listAll,getBatchProductById} from '@/api/system/batch'
export default {
  name: "Order",
  data() {
    return {
      user:this.$store.state.user.userInfo,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderSn: null,
        batchId: null,
        userId: null,
        memberUsername: null,
        totalAmount: null,
        purchasePrice: null,
        status: null,
        autoConfirmDay: null,
        deleteStatus: null,
        receiveTime: null,
        deptId:null,
        pmsBatch:{
          name:''
        }
      },
      batchList:[],
      productList:[],
      orderProductList:[],
      isCardShow: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    // this.loadTestAdd();
    // this.loadTestGet();
    this.loadBatchList();
  },
  methods: {
    handleDeleteProduct(index) {
      this.orderProductList.splice(index, 1);
    },
    addBatchProduct(batchId,orderId){
      let entity = {
        "omsOrderProductId": null,
        "orderId": orderId,
        "productId": null,
        "batchId": batchId,
        "productNumber": 0,
      };
      this.isCardShow = false;
      this.orderProductList.push(entity);
      this.isCardShow = true;
    },
    batchChange(id){
      getBatchProductById(id).then(res=>{
        this.productList = res.data.pmsProducts;
      })
    },
    loadBatchList(){
      listAll('').then(res=>{
        this.batchList = res.data;

      })
    },
    
    loadTestGet(){
      // getOrderProductList().then(res=>{
      //   console.log(res.data)
      //   // debugger
        
      // })

      let up = {
    "omsOrder": {
        "createBy": "",
        "createTime": null,
        "updateBy": "",
        "updateTime": null,
        "remark": null,
        "orderId": 1,
        "orderSn": "No9527",
        "batchId": 6,
        "userId": 1,
        "memberUsername": "admin",
        "totalAmount": null,
        "purchasePrice": null,
        "status": null,
        "autoConfirmDay": null,
        "deleteStatus": null,
        "receiveTime": null
    },
    "orderProductList": [
       
        {
            "createBy": null,
            "createTime": null,
            "updateBy": null,
            "updateTime": null,
            "remark": null,
            "omsOrderProductId": 1,
            "orderId": 1,
            "productId": 66,
            "batchId": 6,
            "productNumber": 100,
        },
        {
            "createBy": null,
            "createTime": null,
            "updateBy": null,
            "updateTime": null,
            "remark": null,
            "omsOrderProductId": 1,
            "orderId": 1,
            "productId": 63,
            "batchId": 6,
            "productNumber": 100,
        }
      ]}
      updateOrderProducts(up).then(res=>{
        // debugger
      })
    },
    loadTestAdd(){
      let order = {
        orderId: null,
        orderSn: 66652,
        batchId: 6,
        userId:this.$store.state.user.id,
        memberUsername: null,
        totalAmount: null,
        purchasePrice: null,
        status: null,
        autoConfirmDay: null,
        deleteStatus: null,
        receiveTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      let p = {
        omsOrderProductId: null,
        orderId: null,
        productId: 64,
        batchId: 6,
        productNumber: 50
      };
      let l = [];
      l.push(p);
      let s = {
        omsOrder:order,
        orderProductList:l
      };
      addOrderProducts(s).then(res=>{
        // debugger
      })
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        // debugger
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
//       {
//     "createBy": "admin",
//     "createTime": "2024-11-07 15:45:18",
//     "updateBy": null,
//     "updateTime": null,
//     "remark": "管理员",
//     "params": {
//         "@type": "java.util.HashMap"
//     },
//     "userId": 1,
//     "deptId": 100,
//     "userName": "admin",
//     "nickName": "管理员",
//     "email": "ry@163.com",
//     "phonenumber": "15888888888",
//     "sex": "1",
//     "avatar": null,
//     "password": "$2a$10$7JB720yubVSZvUI0rEqK/.VqGOZTH.ulu33dHOiBE8ByOhJIrdAu2",
//     "status": "0",
//     "delFlag": "0",
//     "loginIp": "127.0.0.1",
//     "loginDate": "2024-12-04T14:04:51.000+08:00",
//     "dept": {
//         "createBy": null,
//         "createTime": null,
//         "updateBy": null,
//         "updateTime": null,
//         "remark": null,
//         "params": {
//             "@type": "java.util.HashMap"
//         },
//         "deptId": 100,
//         "parentId": 0,
//         "ancestors": "0",
//         "deptName": "江苏省医疗器械检验所",
//         "orderNum": 0,
//         "leader": "江苏",
//         "phone": null,
//         "email": null,
//         "status": "0",
//         "delFlag": null,
//         "parentName": null,
//         "children": []
//     },
//     "roles": [
//         {
//             "createBy": null,
//             "createTime": null,
//             "updateBy": null,
//             "updateTime": null,
//             "remark": null,
//             "params": {
//                 "@type": "java.util.HashMap"
//             },
//             "roleId": 1,
//             "roleName": "超级管理员",
//             "roleKey": "admin",
//             "roleSort": 1,
//             "dataScope": "1",
//             "menuCheckStrictly": false,
//             "deptCheckStrictly": false,
//             "status": "0",
//             "delFlag": null,
//             "flag": false,
//             "menuIds": null,
//             "deptIds": null,
//             "permissions": null,
//             "admin": true
//         }
//     ],
//     "roleIds": null,
//     "postIds": null,
//     "roleId": null,
//     "admin": true
// }
      this.form = {
        orderId: null,
        orderSn: null,
        batchId: null,
        userId:this.$store.state.user.userInfo.userId,
        memberUsername: this.$store.state.user.userInfo.nickName,
        totalAmount: null,
        purchasePrice: null,
        status: null,
        autoConfirmDay: null,
        deleteStatus: null,
        receiveTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId:this.$store.state.user.userInfo.dept.deptId,
        deptName:this.$store.state.user.userInfo.dept.deptName
      };
      this.orderProductList=[];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.form =  {orderId: null,
        orderSn: null,
        batchId: null,
        userId:null,
        memberUsername: null,
        totalAmount: null,
        purchasePrice: null,
        status: null,
        autoConfirmDay: null,
        deleteStatus: null,
        receiveTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId:null,
        deptName:null};
        this.orderProductList=[];
      const orderId = row.orderId || this.ids
      let f = {orderId:orderId}

      getOrderProductList(f).then(response => {
// debugger
        this.form = response.data[0].omsOrder;
        this.batchChange(this.form.batchId);
        this.orderProductList=response.data[0].orderProductList;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let entity = {
              omsOrder:this.form,
              orderProductList:this.orderProductList
            };
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            // updateOrder(this.form).then(response => {
            //   this.$modal.msgSuccess("修改成功");
            //   this.open = false;
            //   this.getList();
            // });
            
            updateOrderProducts(entity).then(res=>{
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            addOrderProducts(entity).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delOrder(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download('system/order/export', {
      //   ...this.queryParams
      // }, `order_${new Date().getTime()}.xlsx`)
// debugger
      this.download('system/order/exportOrderExcel', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
